package com.singletonapps.evory.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.singletonapps.evory.dao.UserDao;
import com.singletonapps.evory.entities.Role;
import com.singletonapps.evory.entities.User;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	private UserDao userDao;
	

	@Override
	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		
		User user = userDao.findUserByName(userName);
		
		if(user != null){
			String password = user.getPassword();
			boolean enabled = user.getStatus() == 1;
			boolean accountNonExpired = user.getStatus() == 1;
			boolean credentialsNonExpired = user.getStatus() == 1;
			boolean accountNonLocked = user.getStatus() == 1;
			
			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			
			for (Role role : user.getRole()) {
				authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
			}
			
			org.springframework.security.core.userdetails.User securityUser = new 
					org.springframework.security.core.userdetails.User(userName, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
			
			return securityUser;
		}else{
			throw new UsernameNotFoundException("User not found!!!");
		}
		
	}

}
